from db_planManager import PlanManager
from db_userManager import UserManager


class PlanSystem:
    def __init__(self):
        self.plan_manager = PlanManager()
        self.user_manager = UserManager()
        self.valid_frequencies = {'daily', 'weekly', 'biweekly'}
        self.valid_statuses = {'active', 'completed', 'paused'}

    def validate_plan_data(self, plan_data):
        """验证计划数据"""
        required_fields = ['patient_id', 'therapist_id', 'plan_name', 'start_date', 'end_date']
        for field in required_fields:
            if field not in plan_data or not plan_data[field]:
                raise ValueError(f"缺少必要参数: {field}")
        if 'frequency' in plan_data and plan_data['frequency'] not in self.valid_frequencies:
            raise ValueError(f"无效的频率参数: {plan_data['frequency']}")
        if 'status' in plan_data and plan_data['status'] not in self.valid_statuses:
            raise ValueError(f"无效的状态参数: {plan_data['status']}")

    def get_patient_list(self, therapist_id):
        """获取治疗师负责的患者列表"""
        try:
            if not self.user_manager.is_therapist(therapist_id):
                return None, "无权限查看患者列表"
            patients = self.plan_manager.get_patient_list()
            return patients
        except Exception as e:
            print(f"获取患者列表失败: {e}")
            return None, "获取患者列表失败"

    def add_rehab_plan(self, plan_data):
        """创建康复计划（服务层）"""
        try:
            self.validate_plan_data(plan_data)
            plan_data.setdefault('frequency', 'daily')
            plan_data.setdefault('status', 'active')
            plan_id = self.plan_manager.create_rehab_plan(plan_data)
            return True, plan_id
        except ValueError as e:
            return False, str(e)
        except Exception as e:
            return False, f"创建计划失败: {str(e)}"

    def update_rehab_plan(self, plan_data):
        """更新康复计划（服务层）"""
        try:
            if 'plan_id' not in plan_data:
                raise ValueError("缺少计划ID")
            # self.validate_plan_data(plan_data) # 不需要检验患者id
            success = self.plan_manager.update_plan(plan_data)
            return success, "更新成功" if success else "未找到匹配计划"
        except ValueError as e:
            return False, str(e)
        except Exception as e:
            return False, f"更新计划失败: {str(e)}"

    def delete_rehab_plan(self, therapist_id, plan_id):
        """删除康复计划"""
        try:
            # 验证计划存在
            plan = self.plan_manager.get_plan_details(plan_id)
            if not plan:
                return False, "计划不存在"
            # 验证权限
            if plan['therapist_id'] != therapist_id:
                return False, "无权限删除此计划"
            success = self.plan_manager.delete_rehab_plan(plan_id)
            return (True, "计划删除成功") if success else (False, "计划删除失败")
        except Exception as e:
            print(f"删除计划异常: {e}")
            return False, f"系统错误: {str(e)}"

    def get_plan_with_exercises(self, plan_id):
        """获取计划详情及训练项目"""
        try:
            plan = self.plan_manager.get_plan_details(plan_id)
            if not plan:
                return None, "计划不存在"
            exercises = self.plan_manager.get_plan_exercises(plan_id)
            plan['exercises'] = exercises or []
            return plan, "获取成功"
        except Exception as e:
            print(f"获取计划详情异常: {e}")
            return None, f"系统错误: {str(e)}"

    def get_patient_plans(self, patient_id):
        """获取患者的康复计划"""
        try:
            # 从数据库获取数据
            plans = self.plan_manager.get_patient_plans(patient_id)
            # 转换日期格式为字符串
            for plan in plans:
                plan['start_date'] = plan['start_date'].strftime("%Y-%m-%d")
                plan['end_date'] = plan['end_date'].strftime("%Y-%m-%d")
            return plans
        except PermissionError as pe:
            raise pe
        except Exception as e:
            raise Exception(f"获取康复计划失败: {str(e)}")

    def add_exercise_to_plan(self, therapist_id, plan_id, exercise_data):
        """为计划添加训练项目"""
        try:
            # 验证计划存在且属于该治疗师
            plan = self.plan_manager.get_plan_details(plan_id)
            if not plan:
                return False, "计划不存在"
            if plan['therapist_id'] != therapist_id:
                return False, "无权限修改此计划"
            exercise_id = self.plan_manager.add_plan_exercise(plan_id, exercise_data)
            if exercise_id:
                return True, f"训练项目添加成功，ID: {exercise_id}"
            return False, "训练项目添加失败"
        except Exception as e:
            print(f"添加训练项目异常: {e}")
            return False, f"系统错误: {str(e)}"
